package com.kxr.literetrofit.network.request;

import android.util.Log;

import com.kxr.literetrofit.network.ApiService;
import com.kxr.literetrofit.network.HttpManager;
import com.kxr.literetrofit.network.schedulers.SchedulerProvider;
import com.kxr.literetrofit.network.subscriber.CustomObserver;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

/**
 * Created by kongxr on 2019/3/12.
 * 网络请求
 */
public class BaseRequest {

    //get方式
    public static void getWithParams(String url, Map<String, String> params, Observer<ResponseBody> subscriber) {
        HttpManager.getInstance().getRequest().executeGet(url, params)
                .subscribeOn(SchedulerProvider.getInstance().io())
                .observeOn(SchedulerProvider.getInstance().ui())
//                .map(XindunResponse::getData)
                .subscribe(subscriber);
    }

    //post方式 非json格式参数！！
    public static void postWithParams(String url, Map<String, String> params, Observer<ResponseBody> subscriber) {
        HttpManager.getInstance().getRequest().executePost(url, params)
                .subscribeOn(SchedulerProvider.getInstance().io())
                .observeOn(SchedulerProvider.getInstance().ui())
//                .map(XindunResponse::getData)
                .subscribe(subscriber);
    }

    //post方式 json（JsonObject或者JsonArray,参数组成方式由上层决定）
    public static void postWithJson(String url, String json, Observer<ResponseBody> subscriber) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"),json);
        HttpManager.getInstance().getRequest().executePostBody(url, requestBody)
                .subscribeOn(SchedulerProvider.getInstance().io())
                .observeOn(SchedulerProvider.getInstance().ui())
//                .map(XindunResponse::getData)
                .subscribe(subscriber);
    }

    //post方式 map参数
    public static void postWithJsonParams(String url, Map<String, String> params, Observer<ResponseBody> subscriber) {
        JSONObject json =new JSONObject(params);
        String data = json.toString();
        String sign = "sign";//自签名校验
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("data", data);
            jsonObject.put("sign", sign);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"),jsonObject.toString());
        HttpManager.getInstance().getRequest().executePostBody(url, requestBody)
                .subscribeOn(SchedulerProvider.getInstance().io())
                .observeOn(SchedulerProvider.getInstance().ui())
//                .map(XindunResponse::getData)
                .subscribe(subscriber);
    }

      //
//    public static void postWithList(String url, List params, Observer<ResponseBody> subscriber) {
//        JSONArray jsonArray = new JSONArray(params);
//        String data = jsonArray.toString();
//        String sign = MD5Util.stringSM3Digest(data /*+ ServerInterfaceConstant.REQUEST_SING*/);
//        JSONObject jsonObject = new JSONObject();
//        try {
//            jsonObject.put("data", data);
//            jsonObject.put("sign", sign);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//
//        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"),jsonObject.toString());
//        HttpManager.getInstance().getRequest().executePostBody(url, requestBody)
//                .subscribeOn(SchedulerProvider.getInstance().io())
//                .observeOn(SchedulerProvider.getInstance().ui())
////                .map(XindunResponse::getData)
//                .subscribe(subscriber);
//    }

    //独立url post方式 json（JsonObject或者JsonArray）
    public static void totalUrlPost(String url, String json, Observer<ResponseBody> subscriber) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"),json);
        HttpManager.getInstance().getRequest().executePostBodyWithUrl(url, requestBody)
                .subscribeOn(SchedulerProvider.getInstance().io())
                .observeOn(SchedulerProvider.getInstance().ui())
//                .map(XindunResponse::getData)
                .subscribe(subscriber);
    }

    //独立url post方式 map参数
    public static void totalUrlPostWithParams(String url, Map<String, String> params, Observer<ResponseBody> subscriber) {
        JSONObject json =new JSONObject(params);
        String data = json.toString();
        String sign = "sign";
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("data", data);
            jsonObject.put("sign", sign);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"),jsonObject.toString());
        HttpManager.getInstance().getRequest().executePostBodyWithUrl(url, requestBody)
                .subscribeOn(SchedulerProvider.getInstance().io())
                .observeOn(SchedulerProvider.getInstance().ui())
//                .map(XindunResponse::getData)
                .subscribe(subscriber);
    }

    //上传文件
    public static void upLoadFile(String url, Map<String, String> params, File file, Observer<ResponseBody> subscriber) {

        MultipartBody.Part part = MultipartBody.Part.createFormData("uploadFile",file.getName(),RequestBody.create(MediaType.parse("multipart/form-data"), file));
        Map<String, RequestBody> paramsBodyMap = new HashMap<>();
        JSONObject jsonObject =new JSONObject(params);
        Log.d("ExampleUnitTest Ok", "Json ==" +jsonObject.toString() );
        String sign = "sign";
        RequestBody paramsBody = RequestBody.create(MultipartBody.FORM, jsonObject.toString());
        RequestBody signBody = RequestBody.create(MultipartBody.FORM, sign);
        paramsBodyMap.put("reqMsg",paramsBody);
        paramsBodyMap.put("sign",signBody);

        HttpManager.getInstance().getRequest().uploadFile(url, paramsBodyMap, part)
                .subscribeOn(SchedulerProvider.getInstance().io())
                .observeOn(SchedulerProvider.getInstance().ui())
//                .map(XindunResponse::getData)
                .subscribe(subscriber);
    }

    //上传多文件  后台未配置（暂不可用） todo
    public static void upLoadFiles(String url, Map<String, String> params, List<File> files, Observer<ResponseBody> subscriber) {
        JSONObject jsonObject =new JSONObject(params);
        String sign = "sign";
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("reqMsg",jsonObject.toString())
                .addFormDataPart("sign",sign);
        for (File file : files) {
            MultipartBody.Part part = MultipartBody.Part.createFormData("uploadFile[]",file.getName(),RequestBody.create(MultipartBody.FORM, file));
            builder.addPart(part);
        }
        MultipartBody body = builder.build();
        HttpManager.getInstance().getRequest().uploadFiles(url, body)
                .subscribeOn(SchedulerProvider.getInstance().io())
                .observeOn(SchedulerProvider.getInstance().ui())
//                .map(XindunResponse::getData)
                .subscribe(subscriber);
    }

    //下载文件
    public static<T> void downFile(String url, Map<String, String> params, CustomObserver<T> subscriber) {
        JSONObject jsonObject = new JSONObject(params);
        String sign = "sign";
        Map<String, RequestBody> paramsBodyMap = new HashMap<>();
        RequestBody paramsBody = RequestBody.create(MultipartBody.FORM, jsonObject.toString());
        RequestBody signBody = RequestBody.create(MultipartBody.FORM, sign);
        paramsBodyMap.put("reqMsg",paramsBody);
        paramsBodyMap.put("sign",signBody);
        HttpManager.getInstance().getRequest().downFile(url, paramsBodyMap)
                .subscribeOn(SchedulerProvider.getInstance().io())
                .observeOn(SchedulerProvider.getInstance().ui())
//                .map(XindunResponse::getData)
                .subscribe(subscriber);
    }

}
